package com.suitsoft.ut.web.middle.dabian;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springside.modules.utils.web.struts2.Struts2Utils;

import com.google.common.collect.Lists;
import com.suitsoft.ut.commons.Constants;
import com.suitsoft.ut.commons.UserHolder;
import com.suitsoft.ut.entity.account.Authority;
import com.suitsoft.ut.entity.account.Role;
import com.suitsoft.ut.entity.account.User;
import com.suitsoft.ut.entity.base.College;
import com.suitsoft.ut.entity.base.Discipline;
import com.suitsoft.ut.entity.base.Student;
import com.suitsoft.ut.entity.base.Team;
import com.suitsoft.ut.entity.thesis.Thesis;
import com.suitsoft.ut.entity.thesis.ThesisFile;
import com.suitsoft.ut.service.account.AccountManager;
import com.suitsoft.ut.service.base.GroupManager;
import com.suitsoft.ut.service.base.StudentManager;
import com.suitsoft.ut.web.CrudActionSupport;
import com.suitsoft.ut.web.InitListActionSupport;

/**
 * 分配学生 给 团队
 *@author Suineg
 */
@Results({@Result(name=CrudActionSupport.RELOAD,location="select-team",type="redirect")})
public class SelectTeamAction extends InitListActionSupport{
	/**
	 * 
	 */
	private static final long serialVersionUID = 3171227597281073970L;
	/** 日志输出对象 */
	protected final Logger logger = LoggerFactory.getLogger(getClass());
	
	/** 账号管理  */
	private AccountManager accountManager;
	/** 团队管理  */
	private GroupManager groupManager;
	/** 学生管理  */
	private StudentManager studentManager;
	
	/** 可用学院 */
	private List<College> colleges;
	/** 学生集合 */
	private List<Student> stduents;
	/** 已选ID集 */
	private List<Long> checkIds;
	/** 专业 ID */
	private Long did;
	/** 团队ID */
	private Long tid;
	/** 学院ID */
	private Long cid;
	
	
	@Override
	public String execute() throws Exception {
		User loginUser = accountManager.getUser(UserHolder.getLoginUser().getId());
		loginTeacher = teacherManger.findTeacherByUser(loginUser.getId());
		if(loginTeacher == null){
			addActionMessage("请选择教师账号");
			return SUCCESS;
		}
		//判断是什么管理员
		int isWhereAmin = isWhereAdmin(loginUser);
		if(isWhereAmin == 1){
			colleges = collegeManager.getAll();
		}else{
			colleges = collegeManager.getByUser();
		}
		if(tid != null &&tid !=0l){
			List<Team> teams = groupManager.findAllByCollege(groupManager.get(tid).getCollege().getId().toString());
			Struts2Utils.getRequest().setAttribute("teamss", teams);
		}
		return SUCCESS;
	}
	
	/**
	 * 确定 当前登陆是什么管理员
	 * @return 1 - 学校管理员，2 - 学院管理员 ,0 - 不是管理员
	 */
	private int isWhereAdmin(User user){
		for(Role r : user.getRoleList()){
			for(Authority a : r.getAuthorityList()){
				if(Constants.CN_SCHOOL_ADMIN.equals(a.getName())){
					return 1;
				}else if(Constants.CN_COLLEGE_ADMIN.equals(a.getName())){
					return 2;
				}else{
					return 0;
				}
			}
		}
		return 0;
	}
	
	/**
	 * 查询
	 * @return
	 */
	public String query() throws Exception{
		if(did == null && did == 0l){
			addActionMessage("非法操作");
			return RELOAD;
		}
		Discipline discipline = disciplineManager.get(did);
//		stduents = Lists.newArrayList(discipline.getStudentSet());
		stduents = Lists.newArrayList();
		for(Student s : discipline.getStudentSet()){
			thesis = s.getThesis();
			if(thesis == null){
				continue;
			}
			thesisFile = thesis.getThesisFile();
			if(thesisFile == null){
				continue;
			}
			if(thesisFile.getIsSelect() == null || 1L != thesisFile.getIsSelect()){
				continue;
			}
			stduents.add(s);
		}
		List<Discipline> disciplines = Lists.newArrayList(discipline.getCollege().getDiscipline());
		Struts2Utils.getRequest().setAttribute("disciplines", disciplines);
		return execute();
	}
	
	/**
	 * 获取专业
	 */
	public void descipline(){
		String msg = "true";
		if(id == null || id == 0L){
			msg = "false";
		}
		College college = collegeManager.get(id);
		if(college == null){
			msg = "false";
		}
		JSONArray array = new JSONArray();
		JSONObject obj = null;
		for(Discipline d : college.getDiscipline()){
			obj = new JSONObject();
			obj.put("id", d.getId());
			obj.put("name", d.getDisciplineName());
			array.add(obj);
		}
		try {
			PrintWriter out = Struts2Utils.getResponse().getWriter();
			if(array.size() > 0){
				out.print(array.toString());
			}else{
				out.print(msg);
			}
			out.flush();
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/***
	 * 获取团队
	 */
	public void getTeam(){
		String msg = "true";
		if(id == null || id == 0l){
			msg = "false";
		}
		List<Team> teams = groupManager.findAllByCollege(id.toString());
		JSONArray array = new JSONArray();
		JSONObject obj = null;
		for(Team t : teams){
			obj = new JSONObject();
			obj.put("id", t.getId());
			obj.put("name", t.getGroupName());
			obj.put("type", t.getType());
			array.add(obj);
		}
		try {
			PrintWriter out = Struts2Utils.getResponse().getWriter();
			if(array.size() > 0){
				out.print(array.toString());
			}else{
				out.print(msg);
			}
			out.flush();
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	/**
	 * 选择学生到团队
	 * @return
	 */
	public String confirmStudent(){
		if(tid == null || tid == 0l){
			addActionMessage("非法操作");
			return RELOAD;
		}
		if(checkIds == null || checkIds.isEmpty()){
			addActionMessage("请至少选一个学生");
			return RELOAD;
		}
		stduents = studentManager.get(checkIds);
		if(stduents == null){
			addActionMessage("非法操作！");
			return RELOAD;
		}
		Team team = groupManager.get(tid);
		if(team == null){
			addActionMessage("非法操作");
			return RELOAD;
		}
		try {
			for(Student st : stduents){
				st.setGroup(team);
				studentManager.save(st);
			}
			addActionMessage("操作成功");
		} catch (Exception e) {
			e.printStackTrace();
			addActionMessage("操作失败");
			return RELOAD;
		}
		return RELOAD;
	}
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public Thesis getThesis() {
		return thesis;
	}
	public void setThesis(Thesis thesis) {
		this.thesis = thesis;
	}
	public ThesisFile getThesisFile() {
		return thesisFile;
	}
	public void setThesisFile(ThesisFile thesisFile) {
		this.thesisFile = thesisFile;
	}
	@Autowired
	public void setAccountManager(AccountManager accountManager) {
		this.accountManager = accountManager;
	}
	public List<College> getColleges() {
		return colleges;
	}
	public void setColleges(List<College> colleges) {
		this.colleges = colleges;
	}
	public List<Student> getStduents() {
		return stduents;
	}
	public void setStduents(List<Student> stduents) {
		this.stduents = stduents;
	}
	@Autowired
	public void setGroupManager(GroupManager groupManager) {
		this.groupManager = groupManager;
	}

	public List<Long> getCheckIds() {
		return checkIds;
	}

	public void setCheckIds(List<Long> checkIds) {
		this.checkIds = checkIds;
	}
	@Autowired
	public void setStudentManager(StudentManager studentManager) {
		this.studentManager = studentManager;
	}

	public Long getDid() {
		return did;
	}

	public void setDid(Long did) {
		this.did = did;
	}

	public Long getTid() {
		return tid;
	}

	public void setTid(Long tid) {
		this.tid = tid;
	}

	public Long getCid() {
		return cid;
	}

	public void setCid(Long cid) {
		this.cid = cid;
	}
}

